package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class Mytask {
    @Autowired
    private OrderMapper orderMapper;

//    @Scheduled(cron = "0/5 * * * * ?")
//    public void task1() {
//        log.info("定时任务1开始执行");
//    }

    //每隔一分钟把超时订单取消 超过十五分钟没支付就算超时
    @Scheduled(cron = "0 * * * * ?")
    public void processTimeoutOrders() {
        log.info("开始处理超时订单");
        LocalDateTime TimeoutTime = LocalDateTime.now().plusMinutes(-15);
        List<Orders> ordersList=orderMapper.getTimeOutOrders(Orders.PENDING_PAYMENT,TimeoutTime);
        if(ordersList!= null&&ordersList.size()>0)
        {
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("订单支付超时");
                orders.setCancelTime(LocalDateTime.now());
                orderMapper.update(orders);
            }
        }


    }

    //每天凌晨一点将前一个工作日没有还处在派送中的订单取消
    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliveryOrders() {
        log.info("开始处理上一个工作日派送中的订单");
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
        List<Orders> ordersList=orderMapper.getDeliveryOrders(Orders.DELIVERY_IN_PROGRESS,time);
        if(ordersList!= null&&ordersList.size()>0){
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            }
        }


    }
}
